//
//  WMWeight.m
//  WeightMaster
//
//  Created by sungeo on 15/8/14.
//  Copyright (c) 2015年 buddysoft. All rights reserved.
//

#import "WMWeight.h"
#import "WMPhotoCache.h"
#import <DateTools.h>

/**
 *  存储 WMWeightRecord 到 iCloud 时使用的记录类型
 */
NSString * const WMWeightRecord = @"WeightRecord";

/**
 *  存储 WMWeightRecord 对象到 iCloud 时每个属性对应的键值
 */
static NSString * const WMWeightValue = @"WMWeightValue";
static NSString * const WMProfileUUID = @"WMProfileUUID";
static NSString * const WMMeasuringDate = @"WMMeasuringDate";

static const float DefaultWeightValue = 0;

@interface WMWeight(){
    NSURL * _cloudKitPhotoObjectUrl;
    
    UIImage * _localProfileImage;
    UIImage * _cloudKitProfileImage;
}

@end

@implementation WMWeight

- (instancetype)init{
    if (self = [super init]) {
        _value = @(DefaultWeightValue);
        _profileUUID = @"";
        _measuringDate = [NSDate date];
    }
    
    return self;
}

- (instancetype)initWithValue:(NSNumber *)value{
    if(self = [self init]){
        _value = value;
    }
    
    return self;
}

- (UIImage *)profileImage{
    if (_profileUUID.length == 0) {
        // 没有记录图片
        return nil;
    }
    
    // 从图片缓存中加载图片
    return [[WMPhotoCache sharedInstance] imageWithUUID:_profileUUID];
}

// 无人调用
- (void)removeLocallyCachedImage{
    NSURL * localDir = [self cachesDirectoryForProfileImage];
    NSString * filePath = localDir.path;
    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
        NSError * error = nil;
        [[NSFileManager defaultManager] removeItemAtPath:filePath error:&error];
        if (error) {
            NSLog(@"删除缓存照片文件失败 %@ : %@", NSStringFromSelector(_cmd), error.description);
        }
    }
    
    _localProfileImage = nil;
}

- (NSURL *)cachesDirectoryForProfileImage{
    NSURL * cachesDirectory = [[NSFileManager defaultManager] URLForDirectory:NSCachesDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:nil];

    NSString * temporaryName = [_profileUUID stringByAppendingString:@".jpeg"];

    return [cachesDirectory URLByAppendingPathComponent:temporaryName];
}

// 使用记录创建时间的短字符串格式，作为唯一 ID
- (NSString *)weightUUID{
    return [self.measuringDate formattedDateWithStyle:NSDateFormatterShortStyle];
}

#pragma mark - BD iCloud Data source

/**
 *  从体重信息生成一条数据库记录
 *
 *  @return CKRecord object
 */
- (CKRecord *)convertToCKRecord{
    CKRecordID * recordID = [[CKRecordID alloc] initWithRecordName:[self weightUUID]];
    CKRecord * record = [[CKRecord alloc] initWithRecordType:WMWeightRecord recordID:recordID];
    record[WMWeightValue] = _value;
    record[WMMeasuringDate] = _measuringDate;
    
    if (_profileUUID.length != 0) {
        record[WMProfileUUID] = _profileUUID;
    }
    
    return record;
}

// 将本地体重信息更新到已存在的云端记录里
- (void)packingCKRecord:(CKRecord *)record{
    NSString * cloudUUID = record[WMProfileUUID];
    
    record[WMWeightValue] = _value;
    record[WMMeasuringDate] = _measuringDate;
    record[WMProfileUUID] = _profileUUID;
    
    // 删除服务器上的旧图
    if (cloudUUID.length != 0 && ![cloudUUID isEqualToString:_profileUUID]) {
        [[WMPhotoCache sharedInstance] deleteImageWithUUID:cloudUUID];
    }
}


/**
 *  从网络查询得到的 iCloud CKRecord 对象，恢复成一个本地记录对象
 *
 *  @param record 从 iCloud 查询到的对象
 *
 *  @return 恢复后的对象实例
 */

- (instancetype)initFromiCloudRecordObject:(CKRecord *)record{
    if (self = [self init]) {
        _value = record[WMWeightValue];
        _measuringDate = record[WMMeasuringDate];
        _profileUUID = record[WMProfileUUID];
        
        // 从 iCloud 恢复的数据毫无疑问已经保存到 iCloud 了
        self.savedToICloud = @(YES);
    }
    
    return self;
}

- (BOOL)isTheSameDayWith:(WMWeight *)weight{
    return ([_measuringDate dayOfYear] == [weight.measuringDate dayOfYear]);
}

- (BOOL)isEarlierThan:(WMWeight *)weight{
    return ([_measuringDate dayOfYear] < [weight.measuringDate dayOfYear]);
}

- (NSString *)monthAndDayString{
    if (_measuringDate == nil) {
        return @"";
    }
    
    return [NSString stringWithFormat:@"%zd/%zd", _measuringDate.month, _measuringDate.day];
}

@end
